// pages/login/login.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buttonText: ['登陆', '注册'],
    picker: ['用户', '管理员', '审核人'],
    index: 0
  },
  reg() {
    var text = this.data.buttonText
    text.reverse()
    this.setData({
      buttonText: text
    })
  },
  PickerChange(e) {
    console.log(e);
    this.setData({
      index: e.detail.value
    })
  },
  formSubmit: function(e) {
    var web
    if (this.data.buttonText[0] == '登陆')
      web = '/user/login'
    else web = '/user'
    console.log(e.detail.value);
    wx.request({
      url: app.globalData.API + web,
      data: e.detail.value,
      method: "POST",
      header: {
        'cookie': wx.getStorageSync("sessionid"), //读取cookie
        "content-type": "application/json"
      },
      success: function(res) {
        console.log(res.data);
        console.log("[login.js] /user 请求成功", res)
        if (res.data.code == 200) {
          //缓存
          wx.setStorage({
            key: "user",
            data: res.data.data
          });
          app.globalData.isLogin=true
          wx.showToast({
            title: res.data.message,
            icon: 'success',
            success: function() {
              setTimeout(function() {
                wx.switchTab({
                  url: '/pages/home/home',
                })
              }, 2000)
            }
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000,
          })
        }
      },
      fail: res => {
        console.log("[login.js] /user 请求失败", res.data)
      },
      complete: res => {

      }
    })
  },
  backuserInfo(e) {
    var that = this
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      wx.request({
        url: app.globalData.API + "/user",
        method: "PUT",
        data: {
          nick: e.detail.userInfo.nickName,
          sex: e.detail.userInfo.gender,
          avatar: e.detail.userInfo.avatarUrl
        },
        header: {
          'cookie': wx.getStorageSync("sessionid"), //读取cookie
          "content-type": "application/json"
        },
        success: res => {
          console.log("[login.js] /user 请求成功", res)
          if (res.data.code == 200) {
           
          } else if (res.data.code == 400) {

          }
        },
        fail: res => {
          console.log("[login.js] /user 请求失败", res.data)
        },
        complete: res => {

        }
      })

    }
  },
})